/*
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.tsunami.plugins.detectors.rce.torchserve;

import static com.google.common.truth.Truth.assertThat;
import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort;

import com.google.tsunami.proto.AdditionalDetail;
import com.google.tsunami.proto.NetworkService;
import com.google.tsunami.proto.Severity;
import com.google.tsunami.proto.Software;
import com.google.tsunami.proto.TextData;
import com.google.tsunami.proto.TransportProtocol;
import java.io.IOException;
import javax.inject.Inject;
import okhttp3.mockwebserver.MockResponse;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class TorchServeExploiterTest extends TorchServeManagementApiTestBase {
  @Inject private TorchServeExploiter exploiter;

  NetworkService service;

  @Before
  public void setUpNetworkService() {
    service =
        NetworkService.newBuilder()
            .setNetworkEndpoint(
                forHostnameAndPort(mockTorchServe.getHostName(), mockTorchServe.getPort()))
            .setTransportProtocol(TransportProtocol.TCP)
            .setSoftware(Software.newBuilder().setName("torchserve"))
            .setServiceName("http")
            .build();
  }

  private void enqueueMockTorchServeResponse(String response) {
    mockTorchServe.enqueue(new MockResponse().setResponseCode(200).setBody(response));
  }

  private String API_DESCRIPTION_RESPONSE =
      "{\n"
          + "  \"openapi\": \"3.0.1\",\n"
          + "  \"info\": {\n"
          + "    \"title\": \"TorchServe APIs\",\n"
          + "    \"description\": \"TorchServe is a flexible and easy to use tool for serving deep"
          + " learning models\",\n"
          + "    \"version\": \"0.8.1\"\n"
          + "  },\n"
          + "  \"paths\": {\n"
          + "    \"/models\": {\n"
          + "      \"post\": {\n"
          + "        \"description\": \"Register a new model in TorchServe.\",\n"
          + "        \"operationId\": \"registerModel\"\n"
          + "     }\n"
          + "    }\n"
          + "  }\n"
          + "}";

  private String EMPTY_MODELS_RESPONSE = "{\"models\": []}";

  private String getCustomizedMetadataResponse(@Nullable String metadata) {
    return "[{ \"customizedMetadata\" : \"" + (metadata == null ? "" : metadata) + "\" }]";
  }

  @Test
  public void isServiceVulnerable_ifServiceIsNotTorchServe_returnsNull() throws IOException {
    // This is template of Inference API response not Management API (no POST /models)
    enqueueMockTorchServeResponse(
        "{\n"
            + "  \"openapi\": \"3.0.1\",\n"
            + "  \"info\": {\n"
            + "    \"title\": \"TorchServe APIs\",\n"
            + "    \"description\": \"TorchServe is a flexible and easy to use tool for serving"
            + " deep learning models\",\n"
            + "    \"version\": \"0.8.1\"\n"
            + "  },\n"
            + "  \"paths\": {\n"
            + "    \"/metrics\": {\n"
            + "      \"get\": {\n"
            + "        \"description\": \"Get TorchServe application metrics in prometheus"
            + " format.\",\n"
            + "        \"operationId\": \"metrics\"\n"
            + "     }\n"
            + "    }\n"
            + "  }\n"
            + "}");
    assertThat(exploiter.isServiceVulnerable(service)).isNull();
  }

  @Test
  public void isServiceVulnerable_ifServiceIsVulnerableBasic_returnsDetails() throws IOException {
    enqueueMockTorchServeResponse(API_DESCRIPTION_RESPONSE);
    // Generate the JSON response with the array of models:
    // "models": [
    //   {
    //     "modelName": "squeezenet1_1",
    //     "modelUrl": "https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar"
    //   },
    mockTorchServe.enqueue(
        new MockResponse()
            .setResponseCode(200)
            .setBody(
                "{\"models\": [\n"
                    + "{\n"
                    + "  \"status\": \"SUCCESS\",\n"
                    + "  \"modelName\": \"squeezenet1_1\",\n"
                    + "  \"modelUrl\":"
                    + " \"https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar\"\n"
                    + "}]}"));

    TorchServeExploiter.Details details = exploiter.isServiceVulnerable(service);

    assertThat(details).isNotNull();
    assertThat(details.models).containsExactly("squeezenet1_1");
    assertThat(details.getSeverity()).isEqualTo(Severity.LOW);
    assertThat(details.isVerified()).isFalse();
    assertThat(details.generateAdditionalDetails())
        .isEqualTo(
            AdditionalDetail.newBuilder()
                .setDescription("Additional details")
                .setTextData(
                    TextData.newBuilder()
                        .setText(
                            "Callback verification is not enabled in Tsunami configuration, so the"
                                + " exploit could not be confirmed and only the Management API"
                                + " detection is reported. It is recommended to enable callback"
                                + " verification for more conclusive vulnerability assessment.\n"
                                + "Models found on the target:\n"
                                + "  - squeezenet1_1")
                        .build())
                .build());
  }

  @Test
  public void isServiceVulnerable_successfulExploitInStaticMode() throws IOException {
    // Setup the details for STATIC mode
    exploiter.details.exploitationMode = TorchServeExploiter.ExploitationMode.STATIC;
    exploiter.details.staticUrl = "http://mock-static-url.com/model.mar";

    enqueueMockTorchServeResponse(API_DESCRIPTION_RESPONSE);

    // Mocking the response for listing models - assuming an empty list for simplicity
    enqueueMockTorchServeResponse(EMPTY_MODELS_RESPONSE);

    // Mocking the response for removeModelByUrl
    enqueueMockTorchServeResponse(EMPTY_MODELS_RESPONSE);

    // Mocking the response for model registration
    mockTorchServe.enqueue(
        new MockResponse()
            .setResponseCode(200)
            .setBody(
                "{\n"
                    + "  \"status\": \"Model \\\"squeezenet1_1\\\" Version: 1.0 registered with 1"
                    + " initial workers\"\n"
                    + "}"));

    // Mocking the response for model list to confirm the model was registered
    enqueueMockTorchServeResponse("");

    // Mocking the response to hash verification request
    enqueueMockTorchServeResponse(getCustomizedMetadataResponse(null));

    // Mocking the response to adding a log file
    enqueueMockTorchServeResponse(getCustomizedMetadataResponse(null));

    // Mocking the response to system info request
    enqueueMockTorchServeResponse(getCustomizedMetadataResponse("{}"));

    // Perform the exploitation test
    TorchServeExploiter.Details details = exploiter.isServiceVulnerable(service);

    // Assertions
    assertThat(details).isNotNull();
    assertThat(details.exploitationMode).isEqualTo(TorchServeExploiter.ExploitationMode.STATIC);
    assertThat(details.exploitUrl).isEqualTo(exploiter.details.staticUrl);
    assertThat(details.isVerified()).isTrue();
  }
}
